using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace LS.UnityExtensions.Editor
{
    [CustomPropertyDrawer(typeof(TypeSearchAttribute))]
    public sealed class TypeSearchPropertyDrower : PropertyDrawer
    {
        private const string handlerName = "string";
        private const string CustomOptionName = "<Empty>";

        int index = 0;
        List<string> m_TypeNameList = new List<string>();
        string[] m_TypeNameArray;
        bool init = false;
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            EditorGUI.BeginChangeCheck();
            if(property.type == handlerName)
            {
                if (!init)
                {
                    Refresh(property.stringValue);
                    init = true;
                }
                string svalue = property.stringValue;
                if (svalue != m_TypeNameArray[this.index])
                {
                    Refresh(svalue);
                }
                string customLabel = label.text;
                TypeSearchAttribute tsa = (attribute as TypeSearchAttribute);
                if (!string.IsNullOrEmpty(tsa.Label))
                {
                    customLabel = tsa.Label;
                }
                var index = EditorGUI.Popup(position, customLabel, this.index, m_TypeNameArray);
                if(index != this.index)
                {
                    this.index = index;
                    string typeName = m_TypeNameArray[index];
                    if(typeName == CustomOptionName)
                    {
                        typeName = string.Empty;
                    }
                    property.stringValue = typeName;
                }
            }
            else
            {
                EditorGUI.PropertyField(position, property);
            }
            
            if (EditorGUI.EndChangeCheck())
            {
                property.serializedObject.ApplyModifiedProperties();
            }
        }

        private void Refresh(string custom)
        {
            m_TypeNameList.Clear();
            m_TypeNameList.Add(CustomOptionName);
            TypeSearchAttribute att = attribute as TypeSearchAttribute;
            m_TypeNameList.AddRange(LS.UnityExtensions.Editor.Type.GetRuntimeTypeNames(att.SearchType));
            m_TypeNameArray = m_TypeNameList.ToArray();
            index = Mathf.Max(0, m_TypeNameList.IndexOf(custom));
        }
    }
}
